package org.coder.consumer_sentinel_9005.controller;

import com.alibaba.csp.sentinel.adapter.spring.webmvc.callback.BlockExceptionHandler;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.alibaba.csp.sentinel.slots.block.authority.AuthorityException;
import com.alibaba.csp.sentinel.slots.block.degrade.DegradeException;
import com.alibaba.csp.sentinel.slots.block.flow.FlowException;
import com.alibaba.csp.sentinel.slots.block.flow.param.ParamFlowException;
import com.alibaba.csp.sentinel.slots.system.SystemBlockException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Component;

import java.io.PrintWriter;

@Component
public class configBlockExceptionHandler implements BlockExceptionHandler {
    @Override
    public void handle(HttpServletRequest request, HttpServletResponse response, BlockException e) throws Exception {
        response.setStatus(429);
        response.setContentType("application/json;charset=utf-8");
//        response.setCharacterEncoding("UTF-8");
        PrintWriter out =response.getWriter();
        StringBuffer sbf = new StringBuffer("sentinel控制--");
        if(e instanceof FlowException){
            sbf.append("限流异常");
        }else if(e instanceof ParamFlowException){
            sbf.append("热点参数限流异常");
        }else if(e instanceof DegradeException){
            sbf.append("降级异常");
        }else if(e instanceof AuthorityException){
            sbf.append("授权规则异常");
        }else if(e instanceof SystemBlockException) {
            sbf.append("系统规则异常");
        }

        response.getWriter().write(sbf.toString());
        out.flush();
        out.close();
    }
}
